var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
require('./lib/db')  // 引入连接数据的代码
// var indexRouter = require('./routes/index');
// var usersRouter = require('./routes/users');
var app = express();

// 接收请求  get  /list

// 实际请求地址  http://localhost:3000/list
app.get('/list', (req,res)=>{
  // 接收到请求后  自动调用函数
  // 如果有数据库操作

  // 发出响应
  res.json({
    code: 200,
    msg: '成功'
  })

})


/**
 * 在浏览器输入服务端地址
 * localhost:3000 
 * 其实就是在get请求服务端的接口
 */


// view engine setup

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));  // 设置公用的静态资源 public

// app.use('/', indexRouter);
// app.use('/users', usersRouter);


/**
 * 平时的代码写在这个模块
 */

/***
 * node的模块化
 * exports.a = 1
 * exports.b = 1
 * 
 * module.exports = {}
 * 
 * 引入
 * const xxx = require('')
 *
 * 
 */


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
